/*
 * @lc app=leetcode.cn id=543 lang=typescript
 *
 * [543] 二叉树的直径
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

//  思路：深度遍历
//  左右子树分别遍历，返回深度，结果为左右子树深度之和，但因为不一定经过根节点，所以需要记录最大值。
// https://leetcode-cn.com/problems/diameter-of-binary-tree/solution/hot-100-9er-cha-shu-de-zhi-jing-python3-di-gui-ye-/

//  复杂度：O(n) O(hight)

function diameterOfBinaryTree(root: TreeNode | null): number {
    let res = 0
    const depth = (r: TreeNode | null): number => {
        if (!r) return 0
        const left = depth(r.left)
        const right = depth(r.right)
        // 记录当前最大值
        res = Math.max(res, left + right)
        // 返回深度
        return Math.max(left, right) + 1
    }
    depth(root)
    return res

};
// @lc code=end

import { TreeNode } from './type'
const root = new TreeNode(1, new TreeNode(2, new TreeNode(4), new TreeNode(5)), new TreeNode(3))

console.log(diameterOfBinaryTree(root));
